package com.fangs.kotlin_banner.utils

import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.fangs.kotlin_banner.R
import android.graphics.drawable.PictureDrawable
import android.text.TextUtils
import android.app.Activity
import android.content.Context
import android.widget.ImageView
import com.fangs.kotlin_banner.svg.SvgSoftwareLayerSetter

/**
 * Description : 图片加载工具类 使用glide框架封装
 */
object ImageLoaderUtils {
    fun display(context: Context?, imageView: ImageView?, url: String?) {
        if (!canDisply(context, imageView)) return
        Glide.with(context!!).load(url)
            .apply(
                RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.DATA) //是将图片原尺寸缓存到本地。
                    .placeholder(R.drawable.ic_launcher_background)
                    .error(R.drawable.ic_launcher_background)
                    .dontAnimate()
            )
            .into(imageView!!)
    }

    fun displyAny(context: Context, imageView: ImageView, url: String) {
        if (!canDisply(context, imageView, url)) return
        if (url.endsWith(".gif")) {
            Glide.with(context).asGif()
                .diskCacheStrategy(DiskCacheStrategy.DATA)
                .load(url).into(imageView)
        } else if (url.endsWith(".svg")) {
            Glide.with(context).`as`(PictureDrawable::class.java)
                .listener(SvgSoftwareLayerSetter())
                .load(url).into(imageView)
        } else {
            display(context, imageView, url)
        }
    }

    fun displayOnly(context: Context, imageView: ImageView, url: String) { //只显示原图  不用占位图
        if (!canDisply(context, imageView, url)) return
        Glide.with(context).load(url)
            .apply(
                RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.DATA) //是将图片原尺寸缓存到本地。
                    .dontTransform()
                    .dontAnimate()
            )
            .into(imageView)
    }

    private fun canDisply(context: Context, imageView: ImageView, url: String): Boolean {
        return canDisply(context, imageView) && !TextUtils.isEmpty(url)
    }

    private fun canDisply(context: Context?, imageView: ImageView?): Boolean {
        return imageView != null && context != null && (context !is Activity || !context.isFinishing)
    }
}